'use strict';

const Service = require('egg').Service;
const utility = require('utility');
const JWT = require('jsonwebtoken');

class ArticleService extends Service {
    /**
     * 入参
     * {
     *    params: {
     *      title: xxx,
     *      categoryId: xxx,
     *      categoryName: xxx,
     *      author: xxx,
     *      authorId: xxx
     *    },
     *    pageSize: 10,
     *    current: 1
     * }
     * 
     * 
    */
    async list(data, isLogin) { // 文章列表
        // 开启事务
        const result = await this.app.mysql.beginTransactionScope(async conn => {
            let selectQuery = '';
            for (let key in data.params) {
                selectQuery += `${key}='${data.params[key]}',`
            }
            if (selectQuery.length > 0) {
                selectQuery = `where ${selectQuery.substr(0, selectQuery.length - 1)}`;
            }
            try {
                let totalList = await conn.query(`select id from article`);
                let list = await conn.query(`select * from article ${selectQuery} order by update_time desc limit ${(data.current - 1) * data.pageSize}, ${data.pageSize}`);
                const total = totalList.length;
                return {
                    message: 'ok',
                    status: 200,
                    result: {
                        list,
                        pageSize: data.pageSize,
                        current: data.current,
                        totalCount: total,
                        total: Math.ceil(total / data.pageSize)
                    }
                }
            } catch (err) {
                console.log(err);
                return {
                    message: '系统异常，请稍后再试',
                    status: 501,
                    result: null
                };
            }
        }, this.ctx);
        return result;
    }

    async category() { // 分类列表
        // 开启事务
        const result = await this.app.mysql.beginTransactionScope(async conn => {
            try {
                const list = await conn.select('category')
                return {
                    message: 'ok',
                    status: 200,
                    result: {
                        list
                    }
                }
            } catch (err) {
                console.log(err);
                return {
                    message: '系统异常，请稍后再试',
                    status: 501,
                    result: null
                };
            }
        }, this.ctx);
        return result;
    }

    async save(data) { // 保存文章
        // 开启事务
        const result = await this.app.mysql.beginTransactionScope(async conn => {
            try {
                const userInfo = this.ctx.user;
                // 查询作者信息
                const author = await conn.select('user', {
                    where: {
                        id: userInfo.userId
                    }
                });
                if (!author && author.length <= 0) {
                    return {
                        message: '当前作者不存在',
                        status: 501,
                        result: null
                    }
                }
                // 写入文章表
                const insertArticle = await conn.insert('article', [{
                    title: data.title,
                    content: data.content,
                    author_id: userInfo.userId,
                    update_time: Date.now(),
                    category_id: data.categoryId,
                    category_name: data.categoryName,
                    main_img: data.mainImg,
                    brief: data.brief
                }]);
                if (insertArticle.affectedRows !== 1) {
                    console.log('写入文章表出错');
                    return {
                        message: '系统异常，请稍后再试',
                        status: 501,
                        result: null
                    }
                }
                // 更新文章数
                const update = await conn.query(`update user set article_count=${author[0].article_count + 1} where id=${userInfo.userId}`);
                if (update.affectedRows !== 1) {
                    console.log('更新作者文章数出错');
                    return {
                        message: '系统异常，请稍后再试',
                        status: 501,
                        result: null
                    }
                }
                return {
                    message: '新增文章成功',
                    status: 200,
                    result: {
                        id: insertArticle.insertId
                    }
                }
            } catch (err) {
                console.log(err);
                return {
                    message: '系统异常，请稍后再试',
                    status: 501,
                    result: null
                };
            }
        }, this.ctx);
        return result;
    }

    async detail(data, isLogin) { // 文章详情
        // 开启事务
        const result = await this.app.mysql.beginTransactionScope(async conn => {
            try {
                const userInfo = this.ctx.user;
                // 查询文章详情
                const detail = await conn.select('article', {
                    where: {
                        id: data.id
                    }
                });
                if (!detail || detail.length === 0) {
                    return {
                        message: '当前文章不存在',
                        status: 501,
                        result: null
                    }
                }
                // 查询作者信息
                const author = await conn.select('user', {
                    where: {
                        id: detail[0].author_id
                    }
                });
                if (!author || author.length === 0) {
                    console.log('当前文章作者不存在');
                    return {
                        message: '当前文章不存在',
                        status: 501,
                        result: null
                    }
                }
                const result = { ...detail[0], author_name: author[0].nick_name, author_avatar: author[0].author_avatar };

                // 检查当前用户是否点赞
                if (isLogin) {
                    const check = await conn.select('like_relative', {
                        where: {
                            article_id: data.id,
                            like_type: 1,
                            user_id: userInfo.userId
                        }
                    });
                    if (!check || check.length <= 0) { // 没点赞
                        result.is_like = 2;
                    } else {
                        result.is_like = 1;
                    }
                }

                return {
                    message: 'ok',
                    status: 200,
                    result: {
                        detail: result
                    }
                }
            } catch (err) {
                console.log(err);
                return {
                    message: '系统异常，请稍后再试',
                    status: 501,
                    result: null
                };
            }
        }, this.ctx);
        return result;
    }

    async sendComment(data) { // 添加评论
        // 开启事务
        const result = await this.app.mysql.beginTransactionScope(async conn => {
            try {
                const isAuthorJoin = this.ctx.user.userId == data.authorId ? 1 : 2;
                // 如果是一级评论，先查一下已经有几条一级评论了，从而计算楼层数
                const list = await conn.query(`select id from comment where is_parent=1`);
                
                const res = await conn.insert('comment', [{
                    content: data.content,
                    parent_id: data.parentId,
                    article_id: data.articleId,
                    update_time: Date.now(),
                    user_id: this.ctx.user.userId,
                    to_user_id: data.toUserId,
                    is_parent: data.isParent,
                    // user_id=author_id，说明有作者参与
                    author_join: isAuthorJoin,
                    floor: data.isParent == 1 ? list.length + 1 : null
                }])
                if (res.affectedRows !== 1) {
                    console.log('写入评论表出错');
                    return {
                        message: '系统异常，请稍后再试',
                        status: 501,
                        result: null
                    }
                }
                // 如果是二级评论，如果判断有作者参与，则改写对应一级评论的状态
                if (Number(data.isParent) === 2 && isAuthorJoin === 1) {
                    const updateAuthorJoin = await conn.query(`update comment set author_join=1 where id=${data.parentId}`);
                    if (updateAuthorJoin.affectedRows !== 1) {
                        console.log('更新是否有作者参与出错');
                        return {
                            message: '系统异常，请稍后再试',
                            status: 501,
                            result: null
                        }
                    }
                }
                // 查询文章详情
                const detail = await conn.select('article', {
                    where: {
                        id: data.articleId
                    }
                })
                if (!detail || detail.length === 0) {
                    console.log('当前文章不存在');
                    return {
                        message: '当前文章不存在',
                        status: 501,
                        result: null
                    };
                }
                // 更新评论数
                const update = await conn.query(`update article set comment=${detail[0].comment + 1} where id='${data.articleId}'`)
                if (update.affectedRows !== 1) {
                    console.log('更新评论数出错');
                    return {
                        message: '系统异常，请稍后再试',
                        status: 501,
                        result: null
                    }
                }
                return {
                    message: '评论成功',
                    status: 200,
                    result: true
                }
            } catch (err) {
                console.log(err);
                return {
                    message: '系统异常，请稍后再试',
                    status: 501,
                    result: null
                };
            }
        }, this.ctx);
        return result;
    }

    async commentList(data, isLogin) { // 评论列表
        // 开启事务
        const result = await this.app.mysql.beginTransactionScope(async conn => {
            try {
                // 将用户头像、昵称、id存到缓存
                let userList = await this.ctx.service.cache.get('user_list');
                if (!userList) {
                    userList = await conn.query('select id, nick_name, avatar, telephone, email, website, brief from user');
                    await this.ctx.service.cache.set('user_list', userList, 60 * 60);
                }
                // 如果是登录状态，需要查询like_relative表，用于匹配某评论是否被当前用户点赞
                let relation = [];
                if (isLogin) {
                    relation = await conn.select('like_relative', {
                        where: {
                            article_id: data.id,
                            like_type: 2
                        }
                    })
                }
                let queryStr = '';
                if (data.onlyLookAuthor == 1) {
                    queryStr += ' and author_join=1';
                }
                // 查询父评论列表
                let totalList = await conn.query(`select id from comment where article_id=${data.id} and is_parent=1${queryStr}`);
                const total = totalList.length;
                let list = await conn.query(`select * from comment where article_id=${data.id} and is_parent=1${queryStr} order by update_time ${data.order} limit ${(data.current - 1) * data.pageSize}, ${data.pageSize}`);
                if (list.length > 0) {
                    list = addUserInfo(list, userList, isLogin, relation, this.ctx.user.userId);
                    // 查询相关子评论
                    let str = list.map(v => v.id).join(',');
                    let childList = [];
                    childList = await conn.query(`select * from comment where article_id=${data.id} and parent_id in (${str}) order by update_time`);
                    childList = addUserInfo(childList, userList, isLogin, relation, this.ctx.user.userId);
                    const res = [];
                    list.forEach(v => {
                        res.push({
                            ...v,
                            childCommentList: childList.filter(val => val.parent_id === v.id)
                        })
                    });
                    return {
                        message: 'ok',
                        status: 200,
                        result: {
                            list: res,
                            pageSize: Number(data.pageSize),
                            current: Number(data.current),
                            totalCount: total,
                            total: Math.ceil(total / data.pageSize)
                        }
                    }
                } else {
                    return {
                        message: 'ok',
                        status: 200,
                        result: {
                            list: [],
                            pageSize: Number(data.pageSize),
                            current: Number(data.current),
                            totalCount: total,
                            total: Math.ceil(total / data.pageSize)
                        }
                    }
                }
            } catch (err) {
                console.log(err);
                return {
                    message: '系统异常，请稍后再试',
                    status: 501,
                    result: null
                };
            }
        }, this.ctx);
        return result;
    }

    async likeComment(data) { // 给评论点赞
        // 开启事务
        const result = await this.app.mysql.beginTransactionScope(async conn => {
            try {
                const userId = this.ctx.user.userId;
                // 查询当前评论
                const res = await conn.select('comment', {
                    where: {
                        id: data.id
                    }
                })
                if (res.length <= 0) {
                    return {
                        message: '当前评论已删除',
                        status: 501,
                        result: null
                    }
                }
                let likeAddCount = 0;
                // 查询当前用户是否有点赞记录
                const relation = await conn.select('like_relative', {
                    where: {
                        comment_id: data.id,
                        user_id: userId,
                        article_id: data.article_id,
                        like_type: 2
                    }
                });
                if (relation.length === 0) { // 如果没查出来，则新建一条，之后点赞数要+1
                    likeAddCount = 1;
                    const addRelation = await conn.insert('like_relative', [{
                        comment_id: data.id,
                        user_id: userId,
                        article_id: data.article_id,
                        like_type: 2,
                        be_user_id: res[0].user_id
                    }]);
                    if (addRelation.affectedRows !== 1) {
                        console.log('给like_relative表增加记录失败');
                        return {
                            message: '系统异常，请稍后再试',
                            status: 501,
                            result: null
                        };
                    }
                } else { // 如果有记录，则删除这条记录，之后点赞数要-1
                    likeAddCount = -1;
                    const deleteRelation = await conn.delete('like_relative', {
                        id: relation[0].id
                    });
                    if (!deleteRelation) {
                        console.log('删除like_relative表记录失败');
                        return {
                            message: '系统异常，请稍后再试',
                            status: 501,
                            result: null
                        };
                    }
                }
                // 给点赞数+1
                const like = await conn.query(`update comment set like_count=${res[0].like_count + likeAddCount} where id='${data.id}'`)
                if (like.affectedRows === 1) {
                    return {
                        message: `${likeAddCount === 1 ? '点赞成功' : '已取消点赞' }`,
                        status: 200,
                        result: true
                    }
                } else {
                    console.log('更新评论表点赞数失败');
                    return {
                        message: '系统异常，请稍后再试',
                        status: 501,
                        result: null
                    };
                }
            } catch (err) {
                console.log(err);
                return {
                    message: '系统异常，请稍后再试',
                    status: 501,
                    result: null
                };
            }
        }, this.ctx);
        return result;
    }

    async likeArticle(data) { // 给文章点赞
        // 开启事务
        const result = await this.app.mysql.beginTransactionScope(async conn => {
            try {
                const userId = this.ctx.user.userId;
                // 查询当前文章
                const res = await conn.select('article', {
                    where: {
                        id: data.article_id
                    }
                })
                if (res.length <= 0) {
                    return {
                        message: '当前文章已删除',
                        status: 501,
                        result: null
                    }
                }
                let likeAddCount = 0;
                // 查询当前用户是否有点赞记录
                const relation = await conn.select('like_relative', {
                    where: {
                        user_id: userId,
                        article_id: data.article_id,
                        like_type: 1
                    }
                });
                if (relation.length === 0) { // 如果没查出来，则新建一条，之后点赞数要+1
                    likeAddCount = 1;
                    const addRelation = await conn.insert('like_relative', [{
                        user_id: userId,
                        article_id: data.article_id,
                        like_type: 1,
                        be_user_id: res[0].author_id
                    }]);
                    if (addRelation.affectedRows !== 1) {
                        console.log('给like_relative表增加记录失败');
                        return {
                            message: '系统异常，请稍后再试',
                            status: 501,
                            result: null
                        };
                    }
                } else { // 如果有记录，则删除这条记录，之后点赞数要-1
                    likeAddCount = -1;
                    const deleteRelation = await conn.delete('like_relative', {
                        id: relation[0].id
                    });
                    if (!deleteRelation) {
                        console.log('删除like_relative表记录失败');
                        return {
                            message: '系统异常，请稍后再试',
                            status: 501,
                            result: null
                        };
                    }
                }
                // 给点赞数+1
                const like = await conn.query(`update article set like_count=${res[0].like_count + likeAddCount} where id='${data.article_id}'`)
                if (like.affectedRows === 1) {
                    return {
                        message: `${likeAddCount === 1 ? '点赞成功' : '已取消点赞' }`,
                        status: 200,
                        result: true
                    }
                } else {
                    console.log('更新文章表点赞数失败');
                    return {
                        message: '系统异常，请稍后再试',
                        status: 501,
                        result: null
                    };
                }
            } catch (err) {
                console.log(err);
                return {
                    message: '系统异常，请稍后再试',
                    status: 501,
                    result: null
                };
            }
        }, this.ctx);
        return result;
    }
}

function addUserInfo(list, userList, isLogin, relation, currentUserId) { // 给评论列表匹配用户头像、昵称以及是否点赞
    return list.map(v => {
        const user = userList.filter(val => val.id === v.user_id);
        const user2 = userList.filter(val => val.id === v.to_user_id);
        let isLiked = false;
        if (isLogin) {
            const filter = relation.filter(val => val.user_id === currentUserId && v.id === val.comment_id);
            if (filter.length > 0) {
                isLiked = true;
            }
        }
        if (user.length > 0) {
            return { ...v, user_avatar: user[0].avatar, nick_name: user[0].nick_name, isLiked, to_user_avatar: user2[0].avatar, to_user_nick_name: user2[0].nick_name };
        } else {
            console.log('未找到当前用户');
            return false
        }
    })
}

module.exports = ArticleService;